package cn.minhx.mw.dtp.sdk.trigger.job;

import cn.minhx.mw.dtp.sdk.domain.DynamicThreadPoolService;
import cn.minhx.mw.dtp.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.minhx.mw.dtp.sdk.registry.Registry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import static com.alibaba.fastjson2.JSON.toJSONString;

/**
 * 线程池配置上报定时任务
 *
 * @author minhx
 */
@Slf4j
public class ThreadPoolConfigReportJob {

    private final DynamicThreadPoolService dynamicThreadPoolService;
    private final Registry registry;
    private long count = -1; ; // 10分钟输出一次info日志
    long threshold = 12 * 10; // 10分钟输出一次info日志

    public ThreadPoolConfigReportJob(DynamicThreadPoolService dynamicThreadPoolService, Registry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void execReportThreadPoolConfig() {
        boolean infoEnable = ++count % threshold == 0;
        if (infoEnable) {
            log.info("[动态线程池-定时任务]线程池配置上报定时任务触发");
        }
        log.debug("[动态线程池-定时任务]线程池配置上报定时任务触发");
        List<ThreadPoolConfigEntity> configList = dynamicThreadPoolService.getThreadPoolConfigList();
        registry.reportThreadPoolConfigList(configList);
        configList.forEach(registry::reportThreadPoolConfig);
        if (infoEnable) {
            log.info("[动态线程池-定时任务]线程池配置上报定时任务完成 configList={}", toJSONString(configList));
        }
        log.debug("[动态线程池-定时任务]线程池配置上报定时任务完成 configList={}", toJSONString(configList));
    }

}
